/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /**
     时间复杂度：O（n）
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }

        //负数说明该树不平衡
        return getHeight(root) > 0;
    }


    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        //如若发现返回的是负数，则说明该树一定不平衡，一路返回负数
        if(leftHeight < 0) {
            return -1;
        }
        //如若发现返回的是负数，则说明该树一定不平衡，一路返回负数
        int rightHeight = getHeight(root.right);
        if(rightHeight < 0) {
            return -1;
        }

        //如果绝对值<=1 说明当前树平衡，返回高度值
        if(Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight , rightHeight) + 1;
        }else {
            //否则返回负数
            return -1;
        }
    }


    // public boolean isBalanced(TreeNode root) {
    //     if(root == null) {
    //         return true;
    //     }
    //     int h1 = getHeight(root.left);
    //     int h2 = getHeight(root.right);
    //     int h = Math.abs(h1-h2);
    //     if(h >= 2) return false;
    //     return isBalanced(root.left) &&
    //     isBalanced(root.right);
    // }

    // public int getHeight(TreeNode root) {
    //     if (root == null) {
    //         return 0;
    //     }
    //     int leftHeight = getHeight(root.left);
    //     int rightHeight = getHeight(root.right);

    //     return leftHeight > rightHeight
    //             ? leftHeight + 1
    //             : rightHeight + 1;
    // }
}